/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interface.Producao.Inco;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import sft.Logica.Insumos;
import sft.Logica.Producao;
import sft.Principal.Principal;

/**
 *
 * @author Adriano
 */
public class Upload extends javax.swing.JFrame {

    public String filename;
    public List<String[]> lerArquivo;
    private List<Insumos> aten = new ArrayList();
    private List<Insumos> unid = new ArrayList();
    private List<Insumos> convenios = new ArrayList();
    private List<Producao> prod = new ArrayList<>();
    private List<String[]> erros = new ArrayList<>();
    private List<String> convenio = new ArrayList<>();
    private List<Integer> unidade = new ArrayList<>();
    private List<String> atendente = new ArrayList<>();
    private Producao producao;

    public Upload() {
        initComponents();
    }

    public Upload(Producao p) {
        initComponents();
        listas();
        this.producao = p;
        compara();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jProgressBar1 = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("UpLoad"));
        jPanel1.setDoubleBuffered(false);

        jButton2.setText("UPLOAD");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Procurar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jProgressBar1.setStringPainted(true);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        JFileChooser choose = new JFileChooser();
        choose.showOpenDialog(null);
        File file = choose.getSelectedFile();
        if (choose.getSelectedFile() != null) {
            filename = file.getAbsolutePath();
            jTextField1.setText(filename);
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        // TODO add your handling code here:
        //impedir que o programa seja fechado durante a execução
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        jButton1.setEnabled(false);
        jButton2.setEnabled(false);
        //ler o arquivo efetivamente
        lerArquivo = LerInconsistencia.getInstance().lerAquivo(jTextField1.getText());
        traduzir();
        new Thread(new ler()).start();

    }//GEN-LAST:event_jButton2ActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Upload.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Upload.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Upload.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Upload.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Upload().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    /*
     INSERT INTO sft.sft_inco (fk_usua, fk_ncon, fk_conv, fk_unid, fk_aten, inco_os_numos, inco_dt_dtregis, inco_ob_obsinco, inco_st_status) 
     VALUES (1, 1, 1, 1, 1, '999-99999-9999', '2014-02-17', 'teste', 'OK')  
        
     id	| usuario | nconformidade | convenio | unidade | atendente | os	| data | observação | status
     0       1             2            3          4          5        6     7        8          9
     */
    
    private void compara(){
        for (int i = 0; i < convenios.size(); i++) {
            convenio.add(String.valueOf(convenios.get(i).getCod()));
        }
        
        for (int i = 0; i < unid.size(); i++) {
            unidade.add(unid.get(i).getCod());
        }
        
        for (int i = 0; i < aten.size(); i++) {
            atendente.add(aten.get(i).getUser().toUpperCase());
        }
    }
    
    private void traduzir() {
        for (int i = 0; i < lerArquivo.size(); i++) {
            boolean gravar = true;
            String[] get = lerArquivo.get(i);
            Producao p = new Producao();

            p.setUsuario(producao.getUsuario());
            p.setnConformidade(producao.getnConformidade());
            p.setStatus(producao.getStatus());
            p.setData(producao.getData());
            p.setTabela(producao.getTabela());
            p.setCaso("adicionar");

            p.setOS(get[0]);
            p.setObs(get[3] + " - " + get[4] + " - " + get[5]);

            //setar convenios            
            if(convenio.indexOf(get[1]) != -1){
                p.setConvenio(convenios.get(convenio.indexOf(get[1])).getFk_conv());
            }else{
                erro(get[0],get[1],"CONVENIO NAO ENCONTRADO!");
                gravar = false;
            }
            
            //seta Unidade
            if(unidade.indexOf(Integer.parseInt(get[0].split("-")[0])) != -1){
                p.setUnidade(unid.get(unidade.indexOf(Integer.parseInt(get[0].split("-")[0]))).getId());
            }else{
                erro(get[0], get[0].split("-")[0], "POSTO NAO ENCONTRADO!");
                gravar = false;
            }
            
            //modela atendente
            String user = null;
            try{
            if (Integer.parseInt(get[2]) < 100) {
                if (Integer.parseInt(get[2]) < 10) {
                    user = "USER00" + get[2];
                } else {
                    user = "USER0" + get[2];
                }
            } else {
                user = "USER" + get[2];
            }
            }catch(NumberFormatException e){
                System.out.println("HOSPITAL : " + get[2]);
                user = get[2];
            }
            //seta atendente
            if(atendente.indexOf(user) != -1) {
                p.setAtendente(aten.get(atendente.indexOf(user)).getId());
            }else{
                erro(get[0], user, "ATENDENTE NAO ENCONTRADO!");
                gravar = false;
            }
            
            //se não der nenhum erro.
            if(gravar){
                prod.add(p);
            }
        }

    }

    private void listas() {
        convenios = Principal.getConvenios();
        unid = Principal.getUnid();
        aten = Principal.getAten();
    }
    
    public class ler implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < prod.size(); i++) {
                try {
                    ProducaoUploadDao dao = new ProducaoUploadDao();
                    dao.adiciona(prod.get(i));
                    
                    jProgressBar1.setValue((i*100/prod.size())+1);
                } catch (SQLException ex) {
                    erro(prod.get(i).getOS(), "SQLException", ex+"");
                }
            }
            if (erros.size() > 0) {
                excelFile();
            }
            JOptionPane.showMessageDialog(null, "Arquivo lido com sucesso!", "Atenção", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        }
    }

    private void excelFile() {
        try {
            JOptionPane.showMessageDialog(null, "Há " + erros.size() + " OS não lidas!", "ATENÇÃO", JOptionPane.ERROR_MESSAGE);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < erros.size(); i++) {
                sb.append(erros.get(i)[0])
                        .append("\t")
                        .append(erros.get(i)[1])
                        .append("\t")
                        .append(erros.get(i)[2])
                        .append("\n");
            }
            String conteudo = sb.toString();
            try (FileWriter excelFile = new FileWriter("C:\\MKT\\ERROS.xls")) {
                excelFile.write(conteudo);
            }
        } catch (IOException ex) {
            Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void erro(String os, String referencia, String erro) {
        String[] e = {os,referencia,erro};
        erros.add(e);
    }

}
